package com.example.demon.jwt;

import com.example.demon.service.UserDetailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

@Component
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailService userDetailService;
    @Autowired
    private PasswordEncoder passwordEncoder;


    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String inputPassword = authentication.getCredentials().toString();
        String name = authentication.getName();
        UserDetails userDetails = userDetailService.loadUserByUsername(name);
        if (!passwordEncoder.matches(inputPassword, userDetails.getPassword())) {
            throw new BadCredentialsException("用户名或密码错误");
        } else {
            return new UsernamePasswordAuthenticationToken(userDetails, inputPassword, userDetails.getAuthorities());
        }
    }

    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }
}
